<template>
  <div class="box">
    <h2>疫情信息网</h2>
    <!-- 登录的盒子 -->
    <div class="reg-box">
      <!-- 标题的盒子 -->
      <div class="title-box"></div>
      <!-- 注册表单区域 -->
      <el-form ref="loginRef" :model="loginForm" :rules="loginRules">
        <el-form-item prop="username">
          <el-input
            placeholder="请输入用户名"
            v-model="loginForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            placeholder="请输入密码"
            type="password"
            v-model="loginForm.password"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="btn-log" type="primary" @click="loginFn"
            >登录</el-button
          >
          <el-link type="info" @click="$router.push('/reg')">去注册</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { loginAPI } from "@/api";
import { mapMutations } from "vuex";

export default {
  name: "my-login",
  data() {
    return {
      loginForm: {
        /* 表单数据对象 */ username: "" /* 用户名 */,
        password: "" /* 密码 */,
      },
      loginRules: {
        /* 表单规则校验对象 */
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9]{1,10}$/,
            message: "用户名必须是1-10的大小写字母数字",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            pattern: /^\S{6,15}$/,
            message: "密码必须是6-15的非空字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    ...mapMutations(["updateToken"]),
    /* 注册按钮 */
    loginFn() {
      this.$refs.loginRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await loginAPI(this.loginForm);
          if (res.code !== 0) {
            // 登录失败
            this.$message.error(res.message);
          } else {
            // 登录成功
            this.$message.success(res.message);
            // 把token字符串保存到vuex中
            this.updateToken({
              val: res.token,
              username: this.loginForm.username,
              user_pic: res.user_pic,
            });
            // 跳转到布局页
            this.$router.push("/");
            setTimeout(() => {
              location.reload();
            }, 0);
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
@import "../../assets/css/login.css";
</style>
